package com.ukefu.webim.web.handler.api.app;

import com.ukefu.webim.service.repository.ChatMessageRepository;
import com.ukefu.webim.service.repository.ConsultInviteRepository;
import com.ukefu.webim.util.RestResult;
import com.ukefu.webim.util.RestResultType;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.model.CousultInvite;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * @author 舒孝鹏
 */
@RestController
@RequestMapping(value = "/appapi/chatmessage")
public class ApiChatMessageApiController extends Handler {

    @Autowired
    private ChatMessageRepository chatMessageRes;

    @Autowired
    private ConsultInviteRepository consultInviteRepository;

    /**
     * 获取未读消息数量
     *
     * @param userId
     * @param appid
     * @return
     */
    @ApiOperation("获取未读消息数量")
    @RequestMapping(value = "/getNotReadCount", method = RequestMethod.GET)
    public ResponseEntity<RestResult> getNotReadCount(@Valid String userId, @Valid String appid) {

        if (StringUtils.isBlank(userId)) {
            return new ResponseEntity<>(new RestResult(RestResultType.LACKDATA, "userId必传"), HttpStatus.OK);
        }

        List<CousultInvite> ci = consultInviteRepository.findBySnsaccountid(appid);
        if (ci.size() == 0) {
            return new ResponseEntity<>(new RestResult(RestResultType.LACKDATA, "appid不存在"), HttpStatus.OK);
        }
        String orgi = ci.get(0).getOrgi();

        return new ResponseEntity<>(new RestResult(RestResultType.OK, chatMessageRes.countNotReadMessagesByUserId(userId, 0, orgi)), HttpStatus.OK);
    }

    /**
     * 标记消息为已读
     *
     * @param userId
     * @param appid
     * @return
     */
    @ApiOperation("标记消息为已读")
    @RequestMapping(value = "/updateMessageReadStatus", method = RequestMethod.GET)
    public ResponseEntity<RestResult> updateMessageReadStatus(@Valid String userId, @Valid String appid) {
        if (StringUtils.isBlank(userId)) {
            return new ResponseEntity<>(new RestResult(RestResultType.LACKDATA, "userId必传"), HttpStatus.OK);
        }

        List<CousultInvite> ci = consultInviteRepository.findBySnsaccountid(appid);
        if (ci.size() == 0) {
            return new ResponseEntity<>(new RestResult(RestResultType.LACKDATA, "appid不存在"), HttpStatus.OK);
        }
        String orgi = ci.get(0).getOrgi();
        // 标记消息为已读
        chatMessageRes.updateMessageReadStatus(userId, orgi);

        return new ResponseEntity<>(new RestResult(RestResultType.OK, "已标记消息为已读"), HttpStatus.OK);
    }
}
